#!/usr/bin/env node
var express = require('express');
var os = require('os');
var path = require('path');
var fs = require('fs');
var utils = require('./js/utils');
var JSZip = require('jszip');

function getIPAdress() {
    var interfaces = os.networkInterfaces();
    for(var devName in interfaces){
        var iface = interfaces[devName];
        for(var i=0;i<iface.length;i++){
            var alias = iface[i];
            if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                return alias.address;
            }
        }
    }
}

function zipRecurse(zip, dir, zipDir) {
    var dirList = fs.readdirSync(dir);
    dirList.forEach(function(item){
        var fullName = dir + '/' + item;
        if(fs.statSync(fullName).isDirectory()){
            zipRecurse(zip, fullName, zipDir+'/'+item);
        }else{
            zip.folder(zipDir).file(item, fs.readFileSync(fullName));
        }
    });
}
function zipFolder(zip, dir, zipDir) {
    zipRecurse(zip, dir, zipDir);
    return zip.generate({base64:false, compression:'DEFLATE'});
}


var ip = getIPAdress();
var app = express();

app.post('/postfile', function(req, res){
    req.pipe(require('unzipper').Extract({path: "."}));
    req.on('end', function () {
        console.log("success");
        res.end("success");
    });
});

app.get('/getfile', function(req, res){
    var file = req.query.file,
        fullName = path.join(process.cwd(), file);
    console.log(fullName);
    if (fs.existsSync(fullName)) {
        var zip = new JSZip();
        if (fs.statSync(fullName).isDirectory()) {
            res.end(zipFolder(zip, fullName, file), "binary");
        } else {
            fs.readFile(fullName, function(err, data) {
                zip.file(file, data);
                res.end(zip.generate({base64:false, compression:'DEFLATE'}), "binary");
            });
        }
    } else {
        console.log("error file or path");
        res.send("error");
    }
});

app.get('/puttext', function(req, res){
	var text = req.query.text;
	console.log(text);
	utils.copy(text);
	res.send("success");
});

app.get('/gettext', function(req, res){
	utils.paste(function(text) {
		res.send(text);
		console.log("success");
	});
});

app.get('/disconnect', function(req, res){
    res.send("success");
    setTimeout(function(){process.exit();}, 100);
});

function startServer(port) {
    var server = app.listen(port);
    server.on('listening', function () {
        console.log(`http://${ip}:${port}`);
    });
    server.on('error', function (err) {
        startServer(port+1);
    })
}

startServer(4000);
